/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.text.json.jsonfiers;

import java.util.Collection;
import java.util.Iterator;

import org.merak.core.text.json.JsonContext;

public class CollectionJsonfier extends Jsonfier {

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public void render(Object object,JsonContext context) throws Exception {

	    // Cast To Collection
		Collection<?> collection = (Collection<?>) object;
		StringBuffer  json       = context.getBuffer();

		// Base case
		if (collection.isEmpty()) {
			json.append("[]");
			return;
		}

		// Choose the correct jsonfier for objects in the collection
		Iterator<?> iter     = collection.iterator();
		Object      item     = iter.next();
		Jsonfier    jsonfier = context.getJsonfier(item);

		// Render first item
		json.append('[');
		jsonfier.render(item,context);

		// Render other items
		while (iter.hasNext()) {
			json.append(',');                     // Separate items with commas
			jsonfier.render(iter.next(),context); // Render array's item
		}
		json.append(']');

	}
	//****************************************************************************

}
